const  MongoClient = require("mongodb"). MongoClient;

const url="mongodb://localhost:27017";
//////增 删 改 查
function connect(callback){
    MongoClient.connect(url,(err,db)=>{
        if(err) throw err;
        callback(db)
    })
}
//////增
module.exports.insert=(dbname,colname,obj,callback)=>{
    connect((db)=>{
            if(!(obj instanceof Array)){
                obj=[obj]
            }
            db.db(dbname).collection(colname).insertMany(obj,(err,result)=>{
                if(err) throw err;
                console.log("插入数据成功");
                db.close();
               
              callback(result);
            })
    })
}
//删
module.exports.del=(dbname,colname,obj,callback)=>{
    connect((db)=>{
        db.db(dbname).collection(colname).deleteMany(obj,(err,result)=>{
            if(err) throw err;
            console.log("删除多个");
            db.close();
          callback(result)
        })
    })

}
//删除一个
module.exports.delsingle=(dbname,colname,obj,callback)=>{
    connect((db)=>{
        db.db(dbname).collection(colname).deleteOne(obj,(err,result)=>{
            if(err) throw err;
            console.log("删除一个");
            db.close();
            callback(result)
        })
    })
}

//改
module.exports.update=(dbname,colname,obj,ob,callback)=>{
    connect((db)=>{
        db.db(dbname).collection(colname).updateOne(obj,{$set:ob},(err,result)=>{
            if(err) throw err;
            // console.log("改");
           
            db.close();
            callback(result);
        })
    })
}

//查
module.exports.find=(dbname,colname,obj,callback,sort={})=>{
    connect((db)=>{
        db.db(dbname).collection(colname).find(obj).sort(sort).toArray((err,result)=>{
            if(err) throw err;
            console.log("查询成功");
            db.close();
            callback(result);
        })
    })
}
//
module.exports.search=(dbname,colname,obj,skip=0,limit=0,callback)=>{
    connect((db)=>{
        db.db(dbname).collection(colname).find(obj).skip(skip).limit(parseInt(limit)).toArray((err,result)=>{
            if(err) throw err;
            console.log("查询成功");
            db.close();
            callback(result);
        })
    })
}
//////////
module.exports.searchs=(dbname,colname,obj,skip=0,limit=0,sort={},callback)=>{
    connect((db)=>{
        db.db(dbname).collection(colname).find(obj).aggregate({$skip:skip},{$limit:limit},{$sort: sort}).toArray((err,result)=>{
            if(err) throw err;
            console.log("查询成功");
            db.close();
            callback(result);
        })
    })
}